<template>
  <div>
    <zm-form
      :model="form"
      :rules="$product.rules"
      ref="form"
      label-width="150px"
      label-position="right"
    >
      <template v-if="+form.type !== 4">
        <template v-if="!isPointCard">
          <h4 class="pl70">成本效益</h4>
          <zm-form-item label="理论成本" prop="theoryCostPrice">
            <zm-input
              v-model="form.theoryCostPrice"
              placeholder="请输入产品理论成本，用于销售单成本核算"
              class="w300"
              type="number"
            ></zm-input>
          </zm-form-item>
          <zm-form-item label="实际成本" prop="practiceCostPrice">
            <zm-input
              v-model="form.practiceCostPrice"
              placeholder="请输入产品实际成本，用于销售单成本核算"
              class="w300"
              type="number"
            ></zm-input>
          </zm-form-item>
        </template>
        <!-- 类型为点卡展示 -->
        <template v-if="isPointCard">
          <h4 class="pl70">成本效益</h4>
          <zm-form-item label="理论成本" prop="theoryCostPrice">
            <zm-input
              v-model="form.theoryCostPrice"
              placeholder="请输入产品理论成本，用于销售单成本核算"
              class="w300"
              type="number"
            >
              <template slot="append">%</template>
            </zm-input>
          </zm-form-item>
          <zm-form-item label="实际成本" prop="practiceCostPrice">
            <zm-input
              v-model="form.practiceCostPrice"
              placeholder="请输入产品实际成本，用于销售单成本核算"
              class="w300"
              type="number"
            >
              <template slot="append">%</template>
            </zm-input>
          </zm-form-item>
        </template>

        <!-- 配置方式 -->
        <template v-if="isPointCard" class="myPracticeCostPriceType">
          <zm-form-item label="配置方式" prop="practiceCostPriceType">
            <el-select class="w300" v-model="form.practiceCostPriceType" clearable @change="form.proportionData = []">
              <el-option v-for="(item, index) in practiceCostPriceTypeList" :key="index" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
        </zm-form-item>
        </template>

        <!-- 提成配置 -->
        <div class="row-bettow wp100">
          <h4 class="pl70 required-style">提成配置</h4>
          <zm-button
            class="fr"
            @click="onSetConfig('create')"
            v-if="!isPointCard"
          >
            新增
          </zm-button>
          <!-- 类型为点卡且选择固定值的二次弹窗 -->
          <zm-button
            class="fr"
            @click="onPointCardSetConfig('create')"
            v-if="isPointCard && form.practiceCostPriceType === '1'"
          >
            新增
          </zm-button>
           <!-- 类型为点卡且选择区间范围的二次弹窗 -->
          <zm-button
            class="fr"
            @click="onPointCardSetConfig('create')"
            v-if="isPointCard && form.practiceCostPriceType === '2'"
          >
            新增
          </zm-button>
        </div>
        <zm-form-item>
          <zm-table-data
            :data="form.proportionData"
            :columns="Columns"
            :create-fetch="false"
            :table-params="tableParams"
            :show-page="false"
            class="mb"
          />
        </zm-form-item>
        <!-- 销售规则 -->
        <!-- <h4 class="pl70">销售规则</h4>
        <zm-form-item label="销售数量" prop="saleRuleNumber" v-if="!isMovie">
          <zm-form-item prop="saleRuleNumberOperationSymbol" class="dib">
            <el-select
              class="w100"
              v-model="form.saleRuleNumberOperationSymbol"
              placeholder="请选择"
              :disabled="isLimitSaleNumber"
            >
              <el-option label="大于" value="1"></el-option>
              <el-option label="大于等于" value="2"></el-option>
            </el-select>
          </zm-form-item>
          <zm-form-item prop="saleRuleNumber" class="dib">
            <zm-input class="w150" v-model="form.saleRuleNumber" type="number" :disabled="isLimitSaleNumber">
              <template slot="append">张</template>
            </zm-input>
          </zm-form-item>
        </zm-form-item>
        <div class="wp80" v-if="isMovie">
          <zm-form-item prop="saleRuleNumber" class="dib">
            <span>销售数量大于</span>
            <zm-input class="w150" v-model="form.saleRuleNumber" type="number" :disabled="isLimitSaleNumber">
              <template slot="append">张</template>
            </zm-input>
            <span>起售，单笔销售单总额大于</span>
          </zm-form-item>

          <zm-form-item prop="saleTotalPrice" label-width="0" class="dib">
            <zm-input class="w150" v-model="form.saleTotalPrice" type="number" :disabled="isLimitSaleNumber">
              <template slot="append">元</template>
            </zm-input>
            <span> 起售</span>
          </zm-form-item>
        </div> -->
        <!-- 有效期规则 -->
        <div class="row-bettow wp100">
          <h4 class="pl70 required-style">有效期规则</h4>
          <zm-button class="fr" @click="onSetRule('create')">新增</zm-button>
        </div>
        <zm-form-item>
          <zm-table-data
            :data="form.expiredData"
            :columns="expiredColumns"
            :create-fetch="false"
            :table-params="tableParams"
            :show-page="false"
            class="mb"
          />
        </zm-form-item>
        <!-- 新增提成配置弹窗 -->
        <set-config
          v-if="setConfigParams.visible"
          v-model="setConfigParams.visible"
          :row-obj="setConfigParams.rowObj"
          @handle-after="configHandleAfter"
        ></set-config>
        <!-- 新增有效期规则弹窗 -->
        <set-rule
          v-if="setRuleParams.visible"
          v-model="setRuleParams.visible"
          :row-obj="setRuleParams.rowObj"
          @handle-after="ruleHandleAfter"
        ></set-rule>
        <!-- 类型为点卡的提成配置弹窗 -->
        <set-point-card-config
          v-if="setPointCardConfigParams.visible"
          v-model="setPointCardConfigParams.visible"
          :row-obj="setPointCardConfigParams.rowObj"
          @handle-after="pointCardConfigHandleAfter"
        ></set-point-card-config>
      </template>
      <!-- 次卡提成方案模板 -->
      <template v-if="+form.type === 4">
        <zm-button class="mt15 mb10" icon="el-icon-edit" @click="handleSetAll">
          批量设置
        </zm-button>
        <zm-table-data
          :data="tableParams.data"
          :columns="secondCardColumns"
          :fetch="loadList"
          :table-params="tableParams"
          :show-page="true"
          pk="id"
          :create-fetch="false"
        >
        </zm-table-data>

        <!-- 批量设置弹窗 -->
        <set-all
          v-model="isShowSetAll"
          v-if="isShowSetAll"
          @handle-after="setAllCallBack"
          :back-fill-data="backFillData"
        ></set-all>
      </template>
    </zm-form>
    <!-- 方案详情 -->
     <detail-container
      v-if="isShowPlanDetail"
      v-model="isShowPlanDetail"
      :id="planDetailID"
      :is-show-btn="false"
    ></detail-container>
  </div>
</template>

<script>
import tableMixin from '@/mixins/zmTableMixin'
import {
  configColumns,
  expiredColumns,
  movieColumns,
  heartColumns,
  secondCardColumns,
  practiceCostPriceTypeList
} from './const'
import SetConfig from './components/SetConfig'
import SetRule from './components/SetRule'
import SetPointCardConfig from './components/SetPointCardConfig'
import productApis from '@/api/src/product'
import DetailContainer from '@/components/DetailContainer'
import SetAll from './components/SetAll'
import { judgeArrFill } from '@/utils'
export default {
  name: 'StepThree',
  components: { SetConfig, SetRule, SetPointCardConfig, DetailContainer, SetAll },
  mixins: [tableMixin],
  inject: ['$product'],
  data () {
    return {
      practiceCostPriceTypeList,
      setConfigParams: {
        visible: false
      },
      setRuleParams: {
        visible: false
      },
      setPointCardConfigParams: {
        visible: false
      },
      copyLoadList: [],
      isShowPlanDetail: false,
      planDetailID: '',
      isShowSetAll: false,
      isLimitSaleNumber: false, // 是否禁用销售规则input
      backFillData: null // 批量设置数据回填
    }
  },
  computed: {
    form: {
      get () {
        return this.$product.form
      },
      set (val) {
        this.$product.form = val
      }
    },
    Columns () {
      // 点卡
      if (+this.form.type === 3) {
        // // 心选
        // if (this.form.businessType.includes('3')) {
        //   return heartColumns(this)
        // } else {
        //   // 电影
        //   return movieColumns(this)
        // }
        // 区间
        if (this.form.practiceCostPriceType === '1') {
          return heartColumns(this)
        } else {
          // 固定
          return movieColumns(this)
        }
      } else {
        // 兑换券、卖品券
        return configColumns(this)
      }
    },
    expiredColumns () {
      // 有效期规则数据
      return expiredColumns(this)
    },
    secondCardColumns () {
      // 次卡提成方案数据
      return secondCardColumns(this)
    },
    // 类型是点卡
    isPointCard () {
      return +this.form.type === 3
    }
    // isXXcard () {
    //   return this.form.businessType.includes('3')
    // },
    // isMovie () {
    //   return this.isPointCard && !this.isXXcard
    // }
  },
  watch: {
    'form.expiredData': {
      handler (val) {
        if (this.form.expiredData && this.form.expiredData.length > 0) {
          this.isLimitSaleNumber = true
        } else {
          this.isLimitSaleNumber = false
        }
      },
      deep: true,
      immediate: true
    },
    // 类型为点卡，业务类型心选和电影之间切换的时候清空提成配置的数据
    'form.businessType': {
      handler (nVal, oVal) {
        if (oVal && this.form.type === '3' && nVal.includes('3') !== oVal.includes('3')) {
          this.$set(this.form, 'proportionData', [])
        }
      },
      deep: true
    }
  },
  created () {},
  methods: {
    // 新增/编辑提成配置
    onSetConfig (type, row = {}, index = null) {
      if (!this.form.theoryCostPrice) {
        this.$message.warning('请先填写理论成本，再进行提成配置')
        return
      }
      if (type === 'create') {
        if (this.form.proportionData.length >= 20) {
          this.$message.warning('档位提成方案已达上限')
          return
        }
      }
      this.setConfigParams = {
        visible: true,
        rowObj: {
          type,
          row,
          index,
          data: this.form.proportionData,
          theoryCostPrice: this.form.theoryCostPrice // 理论成本
        }
      }
    },
    // 类型为点卡的 新增/编辑提成配置
    onPointCardSetConfig (type, row = {}, index = null) {
      if (!this.form.theoryCostPrice) {
        this.$message.warning('请先填写理论成本，再进行提成配置')
        return
      }
      if (type === 'create') {
        if (this.form.proportionData.length >= 30) {
          this.$message.warning('档位提成方案已达上限')
          return
        }
      }
      this.setPointCardConfigParams = {
        visible: true,
        rowObj: {
          type,
          row,
          index,
          data: this.form.proportionData,
          theoryCostPrice: this.form.theoryCostPrice // 理论成本
        }
      }
    },
    // 新增/编辑有效期规则
    onSetRule (type, row = {}, index = null) {
      if (this.isMovie) {
        this.form.saleRuleNumberOperationSymbol = '1'
      }
      // if (
      //   !this.form.saleRuleNumber ||
      //   !this.form.saleRuleNumberOperationSymbol
      // ) {
      //   this.$message.warning('请先填写销售数量，再设置有效期规则')
      //   return
      // }
      if (type === 'create') {
        if (this.form.expiredData.length >= 20) {
          this.$message.warning('档位有效期方案已达上限')
          return
        }
      }
      this.setRuleParams = {
        visible: true,
        rowObj: {
          type,
          row,
          index,
          data: this.form.expiredData

        }
      }
    },
    // 提成配置操作
    configOperation (type, row, index) {
      switch (type) {
        case 'edit':
          this.onSetConfig('edit', row, index)
          break
        case 'del':
          this.form.proportionData.splice(index, 1)
          break
      }
    },
    // 有效期规则
    expiredOperation (type, row, index) {
      switch (type) {
        case 'edit':
          this.onSetRule('edit', row, index)
          break
        case 'del':
          this.form.expiredData.splice(index, 1)
          break
      }
    },
    // 次卡操作
    secondOperation (type, row, index) {
      switch (type) {
        case 'detail':
          this.isShowPlanDetail = true
          this.planDetailID = row.id
          break
        case 'del':
          this.handleDelProduct(row, index)
          break
      }
    },
    // 提成配置回调
    configHandleAfter (type, val, index) {
      if (type === 'edit') {
        this.form.proportionData[index] = val
      }
      if (type === 'create') {
        this.form.proportionData.push(val)
      }
    },
    // 点卡提成配置回调
    pointCardConfigHandleAfter (type, val, index) {
      // 判断档位是否存在
      const allData = this.form.proportionData
      const repeatArr = allData.filter(item => {
        return +Number(item.minValue).toFixed(2) === +Number(val.minValue).toFixed(2) && ((type === 'edit' && (item.id !== val.id || !val.id)) || type === 'create')
      })
      if (repeatArr && repeatArr.length > 0) {
        this.$message.warning('档位折扣已存在，请重新设置')
        return false
      }

      // 判断结束
      if (type === 'edit') {
        this.form.proportionData[index] = val
      }
      if (type === 'create') {
        this.form.proportionData.push(val)
      }
      this.setPointCardConfigParams = {
        visible: false,
        rowObj: {}
      }
    },
    // 有效期规则回调
    ruleHandleAfter (type, val, index) {
      if (type === 'edit') {
        this.form.expiredData[index] = val
      }
      if (type === 'create') {
        this.form.expiredData.push(val)
      }
    },

    // 表单校验
    async handleFormValidate () {
      let _valid = false
      let msgList = []

      if (this.form.type === '4') {
        // 次卡提成配置必填数据校验
        return new Promise((resolve, reject) => {
          if (
            this.form.proportionTimesData &&
          this.form.proportionTimesData.length > 0
          ) {
          // 对编辑回填的数据提取，只对以下四个值进行非空判断
            const checkList = this.form.proportionTimesData.map(item => {
              return {
                minSaleNumber: item.minSaleNumber, // 最低销售数量
                minSaleNumberOperationSymbol: item.minSaleNumberOperationSymbol, // 最低销售数量运算符号：1大于，2大于等于
                couponNumber: item.couponNumber, // 单张次卡包含兑换券数量
                couponNumberOperationSymbol: item.couponNumberOperationSymbol // 单张次
              }
            })
            if (judgeArrFill(checkList).length > 0) {
              msgList.push('次卡提成配置')
              _valid = false
              _valid ? resolve() : reject(`提成方案：${msgList.join('、')}`)
            } else {
              const arr = this.form.proportionTimesData
              for (let i = 0; i < arr.length; i++) {
                // console.log('proportionTimesData', i)
                if (!/^[1-9]{1,}[\d]*$/.test(arr[i].minSaleNumber)) {
                  this.$message.warning('请设置正整数')
                  _valid = false
                  return
                } else if (!/^[1-9]{1,}[\d]*$/.test(arr[i].couponNumber)) {
                  this.$message.warning('请设置正整数')
                  _valid = false
                  return
                } else {
                  _valid = true
                }
              }
              _valid ? resolve() : reject(`提成方案：${msgList.join('、')}`)
            }
          } else {
            _valid = false
            msgList.push('次卡提成配置')
            _valid ? resolve() : reject(`提成方案：${msgList.join('、')}`)
          }
        })
      } else {
        // 提成配置必填数据校验
        if (this.form.proportionData && this.form.proportionData.length > 0) {
          _valid = true
        } else {
          _valid = false
          msgList.push('提成配置')
        }
        // 有效期规则必填数据校验
        if (this.form.expiredData && this.form.expiredData.length > 0) {
          _valid = true
        } else {
          _valid = false
          msgList.push('有效期规则')
        }
        if (this.form.theoryCostPrice && this.form.proportionData.length > 0) {
          const topOne = this.form.proportionData[0]
          if (this.form.theoryCostPrice > topOne.minValue) {
            return this.$confirm('销售单价低于成本价，确定保存？', '提示', {
              type: 'warning'
            }).then((res) => {
              return Promise.resolve()
            })
          }
        }
        this.$refs.form.validate((valid) => {
          if (valid) {
            _valid = true
          } else {
            _valid = false
          }
        })
        return new Promise((resolve, reject) => {
          _valid ? resolve() : reject(`提成方案：${msgList.join('、')}`)
        })
      }
    },
    async loadList (status) {
      // console.log('第一步调用第三步请求函数')
      if (status === 'no-reload') {
        this.initialTableData(this.copyLoadList, this.copyLoadList.length)
      } else {
        if (!this.form.couponProductId) {
          return
        }
        const _res = await productApis.getPageList(
          this.assignQuery({ ids: this.form.couponProductId, dataType: '-2' })
        )
        // 根据接口数据生成对应条数的数据格式
        let _arr = []
        _res.list.forEach((item) => {
          _arr.push({
            couponProductId: item.id, // 兑换券产品id
            minSaleNumber: '', // 最低销售数量
            minSaleNumberOperationSymbol: '', // 最低销售数量运算符号：1大于，2大于等于
            couponNumber: '', // 单张次卡包含兑换券数量
            couponNumberOperationSymbol: '' // 单张次卡包含兑换券数量运算符号：1大于，2大于等于
          })
        })
        // 次卡数据回填
        if (this.$product.id) {
          _arr = _arr.map((item) => {
            this.form.proportionTimesData.forEach((_item) => {
              if (item.couponProductId === _item.couponProductId) {
                item = _item
              }
            })
            return item
          })
        }
        this.$set(this.form, 'proportionTimesData', _arr)
        this.initialTableData(_res.list, _res.count)
      }
    },
    // 删除产品数据，并删除对应id
    handleDelProduct (row, index) {
      this.copyLoadList = JSON.parse(JSON.stringify(this.tableParams.data))
      this.copyLoadList = this.copyLoadList.filter(
        (item) => item.id !== row.id
      )
      const _proportionTimesData = this.form.proportionTimesData.filter(
        (item) => item.couponProductId !== row.id
      )
      this.$set(this.form, 'proportionTimesData', _proportionTimesData)
      this.loadList('no-reload')
      const _arr = this.form.couponProductId.split(',')
      _arr.splice(_arr.indexOf(row.id), 1)
      this.$set(this.form, 'couponProductId', _arr.join(','))
    },
    handleSetAll () {
      this.isShowSetAll = true
    },
    // 批量设置回调
    setAllCallBack (val) {
      this.backFillData = val
      const res = this.form.proportionTimesData.map((item) => {
        return {
          ...item,
          ...val
        }
      })
      this.$set(this.form, 'proportionTimesData', res)
    }
  }
}
</script>

<style scoped lang='scss'>
// .myPracticeCostPriceType{
//   /deep/.el-form-item__label{
//     font-size:20px ;
//   }
// }
</style>
